//
//  SourceIntroViewController.swift
//  test
//
//  Created by colin on 2019/3/29.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit
import MJRefresh

class SourceIntroViewController: ScrollViewController {

    private var infoData:JSONObject?
    private lazy var infoTableView = UITableView(frame: CGRect.zero, style: .grouped)
    private lazy var cellHeights = [IndexPath:CGFloat]()
    private var headerHeight:CGFloat = 0

    convenience init(data:JSONObject?,headerHeight:CGFloat) {
        self.init()
        self.infoData = data
        self.headerHeight = headerHeight
    }
    
    override func scrollView() -> UIScrollView? {
        return self.infoTableView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        
        self.infoTableView.do {
            $0.register(Cell.self, forCellReuseIdentifier: Cell.reuseId)
            $0.contentInsetAdjustmentBehavior = .never
            $0.sectionHeaderHeight = 0
            $0.sectionFooterHeight = 0
            $0.estimatedRowHeight = 0
            $0.estimatedSectionHeaderHeight = 0
            $0.estimatedSectionFooterHeight = 0
            $0.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude))
            $0.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude))
            $0.separatorStyle = .none
            $0.backgroundColor = UIColor.white
            $0.showsVerticalScrollIndicator = false
            $0.dataSource = self
            $0.delegate = self

            $0.contentInset = UIEdgeInsets(top: self.headerHeight, left: 0, bottom: 0, right: 0)
            $0.contentOffset = CGPoint(x: 0, y: -self.headerHeight)
        }
        self.view.addSubview(self.infoTableView)
        self.infoTableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
    }
    
}

// MARK: - Cell
extension SourceIntroViewController {
    
    class Cell: UITableViewCell {
        
        static let reuseId = "CellSourceIntro"
        var cellHeight:CGFloat = 0
        
        private lazy var contentWebView = CLEmbededWebView(frame: CGRect.zero)
        private var heightChangedHandle:((_ height_:CGFloat)->Void)?
        
        func refresh(html:String?,heightChangedHandle:((_ height_:CGFloat)->Void)?) {
            self.heightChangedHandle = heightChangedHandle
            self.contentWebView.content = html
        }
        
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            self.selectionStyle = .none
            self.backgroundColor = UIColor.clear
            self.contentView.backgroundColor = UIColor.clear
            
            self.contentWebView.webViewHeightChanged = { [weak self] (height_) in
                self?.cellHeight = height_
                self?.heightChangedHandle?(height_)
            }
            self.contentView.addSubview(self.contentWebView)
            self.contentWebView.snp.makeConstraints { (make) in
                make.left.equalToSuperview().offset(15.0)
                make.right.equalToSuperview().offset(-15.0)
                make.top.bottom.equalToSuperview()
            }
            
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
}

// MARK: - UITableViewDataSource
extension SourceIntroViewController : UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if let infoData_ = self.infoData,!infoData_.isEmpty {
            return 1
        } else {
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: Cell.reuseId) as! Cell
        let html = self.infoData?["content"] as? String
        cell.refresh(html: html, heightChangedHandle: { [weak self] (height_) in
            self?.cellHeights[indexPath] = height_
            self?.infoTableView.reloadRows(at: [indexPath], with: .fade)
        })
        self.cellHeights[indexPath] = cell.cellHeight
        return cell
    }
    
}

// MARK: - UITableViewDelegate
extension SourceIntroViewController : UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if let height = self.cellHeights[indexPath] {
            return height
        } else {
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if let infoData_ = self.infoData,!infoData_.isEmpty {
            let headerView = UIView().then {
                let tagView = UIView()
                tagView.backgroundColor = UIColor(hex: "AE1600")
                $0.addSubview(tagView)
                tagView.snp.makeConstraints({ (make) in
                    make.left.equalToSuperview()
                    make.size.equalTo(CGSize(width: 3.0, height: 20.0))
                    make.centerY.equalToSuperview()
                })
                
                let labelTitle = UILabel().then {
                    $0.textColor = UIColor(hex: "343434")
                    $0.font = UIFont.systemFont(ofSize: 17.0, weight: .bold)
                    $0.text = "简介"
                }
                $0.addSubview(labelTitle)
                labelTitle.snp.makeConstraints({ (make) in
                    make.left.equalTo(tagView.snp.right).offset(15.0)
                    make.centerY.equalToSuperview()
                })
                
            }
            return headerView
        } else {
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if let infoData_ = self.infoData,!infoData_.isEmpty {
            return 40.0
        } else {
            return CGFloat.leastNormalMagnitude
        }
    }
}

// MARK: - UIScrollViewDelegate
extension SourceIntroViewController : UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.scrollHandle?(self.index,scrollView)
    }

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if !decelerate {
            self.endDecelerating?(self.index,scrollView)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.endDecelerating?(self.index,scrollView)
    }
}
